﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using PBMessage;
using Clojure;
public class GameScene : BaseScene
{

    GameObject SceneObject;
    public List<ReadRoomPlayer> ReadyPlayClamp0;
    public List<ReadRoomPlayer> ReadyPlayClamp1;
    public CameraController SceneCamera;


    public List<GamePlayer> GamePlayers = new List<GamePlayer>();
    public GamePlayer LocalPlayer;

    public override void OnLoad(params object[] args)
    {
        UnitManager.Instance.InitRootGameObject();
        ReadyPlayClamp0 = (List<ReadRoomPlayer>)args[0];
        ReadyPlayClamp1 = (List<ReadRoomPlayer>)args[1];
        SceneObject =(GameObject)GameObject.Instantiate(Resources.Load("Prefab/Scene/Scene"));
        SceneObject.transform.localPosition = Vector3.zero;

        SceneCamera = Camera.main.gameObject.AddComponent<CameraController>();
        SceneCamera.OnLoad();

        RT.LoadASTTree("SceneTrigger", GameTrigger.Instance.GetTriggerConfigPath());

        GameTrigger.Instance.Init("SceneTrigger");

        GameTrigger.Instance.ClojureContext.Define("players-count", new NumberNode(ReadyPlayClamp0.Count+ReadyPlayClamp1.Count, NumberNode.NumberType.INT));

        GameTrigger.Instance.Load("SceneTrigger");

        GameTrigger.Instance.CallEvent("GameLoad");
    }


    public override void OnUpdate()
    {
        GameTrigger.Instance.Update();
        OnTuchScene();

    }

    public override void OnExit()
    {
        GameTrigger.Instance.Destory();
    }

    public GamePlayer GetGamePlayer(int playerID) 
    {
        if (playerID > GamePlayers.Count) 
        {
            return null;
        }
        return GamePlayers[playerID];
    }

    void OnTuchScene()
    {
        if (Input.GetMouseButtonDown(1)) 
        {
          Ray ray =   Camera.main.ScreenPointToRay(Input.mousePosition);
          RaycastHit hit;

          if (Physics.Raycast(ray, out hit) && hit.transform.gameObject.name == "Terrain") 
          {
              Game.Event.CallEvent("SceneClick",hit.point);
          }
          if (Physics.Raycast(ray, out hit) && hit.transform.gameObject.tag  == "Unit") 
          {
              Game.Event.CallEvent("UnitClick",hit.point,hit.transform.parent.gameObject.GetComponent<Unit>());
          }
        }
    }
}
